#include <fstream>
#include <iostream>
#include <string>

#include "contacts.pb.h"

void printContacts(const contacts::Contacts& contacts) {
    for (int i = 0; i < contacts.people_info_size(); ++i) {
        printf("-----------the %dst information-----------\n", i + 1);

        contacts::PepoleInfo people_info = contacts.people_info(i);
        printf("name: %s\n", people_info.name().c_str());
        printf("age: %d\n", people_info.age());
        for (int j = 0; j < people_info.phones_size(); ++j) {
            contacts::Phone phone = people_info.phones(j);
            printf("the %dst phone number: %s   %s\n", j + 1,
                   phone.number().c_str(),
                   phone.PhoneType_Name(phone.phone_type()).c_str());
        }

        if (people_info.has_any() &&
            people_info.any().Is<contacts::Address>()) {
            contacts::Address address;
            people_info.any().UnpackTo(&address);

            if (!address.home_address().empty()) {
                printf("home address: %s\n", address.home_address().c_str());
            }
            if (!address.unit_address().empty()){
                printf("util address: %s\n", address.unit_address().c_str());
            }
        }

        // if (people_info.has_qq()){
        //     printf("QQ: %s\n", people_info.qq());
        // }else if (people_info.has_wechat()){
        //     printf("WeChat: %s\n", people_info.wechat());
        // }

        switch (people_info.other_contact_case()){
            case contacts::PepoleInfo::OtherContactCase::kQq:  
                printf("QQ: %s\n", people_info.qq().c_str());
                break;
            case contacts::PepoleInfo::OtherContactCase::kWechat:  
                printf("WeChat: %s\n", people_info.wechat().c_str());
        }

        if (!people_info.note().empty()){
            printf("note:\n");
            for (auto& it : people_info.note()){
                printf("\t%s: %s\n", it.first.c_str(), it.second.c_str());
            }
        }
    }
}

int main() {
    contacts::Contacts contacts;

    // 1. 读取本地通讯录
    std::fstream input("contacts.txt", std::ios::in | std::ios::binary);
    if (contacts.ParseFromIstream(&input) == false) {
        std::cout << "parse failed" << std::endl;

        input.close();
        return -1;
    }

    // 2. 对通讯录的内容进行打印
    printContacts(contacts);

    return 0;
}
